<template>
	<z-paging v-if="firstLoaded || isCurrentPage" key="declaration" ref="paging" v-model="dataList" @query="queryList" :empty-view-center="false" :hide-no-more-by-limit="10">
		<template v-slot:top>
			<!-- 	<view class="searchBox" id="searchBox">
				<uni-search-bar placeholder="搜索商品名称、装车地点、卸车地点" @input="(e) => queryList(null, null, e)"></uni-search-bar>
			</view> -->
			<!-- 已完成时展示的运费状态筛选 -->
			<drop-down-vue v-if="Props.type == 2" @ok="dropOk" />
		</template>
		<view class="box">
			<view v-for="(vd, index) in dataList" :key="vd.id">
				<view class="box">
					<!-- 关注的行业 搜索 -->
					<view
						:class="['container', index + 1 != dataList.length && 'conLines', vd?.dataChangeMsgs?.length && 'notify']"
						:key="index"
						@click="
							navTo(`/pages/logisticsCompany/myDeclaration/freightDetails/freightDetails`, {
								data: {
									outside: vd,
									item: vd
								}
							})
						"
					>
						{{ dataChangeMsgs }}
						<u-alert-tips v-if="vd?.dataChangeMsgs?.length" type="warning" title="" :description="descriptionGet(vd?.dataChangeMsgs)"></u-alert-tips>
						<view class="shopType">
							<text>车号:{{ vd.vehicleNo }}</text>

							<view class="freightDetails">
								<u-icon color="#51a9ec" label-color="#51a9ec" label-size="26" label="运费详情" size="20" name="arrow-right" label-pos="left"></u-icon>
							</view>
						</view>
						<view class="con">
							<view class="item">
								<text class="type">装车日期:</text>
								<text>{{ vd.loadingTime }}</text>
							</view>
							<view class="item">
								<text class="type">装车地点:</text>
								<view class="rightBox">
									<text class="text">{{ vd.loadingAddress }}</text>
									<image class="img" src="/static/area.png" mode="widthFix"></image>
								</view>
							</view>
							<view class="item">
								<text class="type">卸车地点:</text>
								<view class="rightBox">
									<text class="text">{{ vd.unloadAddress }}</text>
									<image class="img" src="/static/area.png" mode="widthFix"></image>
								</view>
							</view>
							<view class="item">
								<text class="type">运费单价:</text>
								<text>
									<!-- 如果车辆没有单独的单价，那就读取订单的单价 -->
									<!-- 如果车辆有单独的单价，那就读取单独的单价 -->
									{{ vd.freightPrice / 1000 }}
									<text class="unit">元</text>
								</text>
							</view>
							<view class="item" v-if="vd.vehicleState >= 4">
								<text class="type">运费金额:</text>
								<text>
									<!-- 如果车辆没有单独的单价，那就读取订单的单价 -->
									<!-- 如果车辆有单独的单价，那就读取单独的单价 -->
									{{ vd.freightAmount / 1000 }}
									<text class="unit">元</text>
								</text>
							</view>

							<view class="item">
								<text class="type">车辆状态:</text>
								<text v-if="vd.vehicleState == 1">未到厂</text>
								<text v-if="vd.vehicleState == 2">已到厂</text>
								<text v-if="vd.vehicleState == 3">已装车</text>
								<text v-if="vd.vehicleState == 4">已卸车</text>
								<text v-if="vd.vehicleState == 5">已完成</text>
								<text v-if="!vd.vehicleState">--</text>
							</view>
							<!-- 只有卸车之后 才有运费状态 -->
							<view class="item" v-if="vd.vehicleState >= 4">
								<text class="type">运费状态:</text>
								<!--  过磅单未确认 （审计审批后才算是审核中） -->
								<text v-if="vd.confirmState == 1">
									<u-tag v-if="vd.flowStep == 0" text="未审核" type="info" size="mini" />
									<u-tag v-if="vd.flowStep == 1" text="审核中" type="warning" size="mini" />
								</text>
								<!--  过磅单已确认并且👇  -->
								<view v-if="vd.confirmState == 2">
									<!-- 运费状态 = 2 -->
									<text v-if="vd.freightState == 2">
										<u-tag text="已审核" type="primary" size="mini" />
									</text>
									<!-- 运费状态 = 2 -->
									<text v-if="vd.freightState == 3">
										<u-tag text="已付款" type="success" size="mini" />
									</text>
								</view>
							</view>
							<view class="item" v-if="vd.confirmState == 2 && vd.freightState == 3">
								<text class="type">付款时间:</text>
								<text>
									<!-- 如果车辆没有单独的单价，那就读取订单的单价 -->
									<!-- 如果车辆有单独的单价，那就读取单独的单价 -->
									{{ vd.freightPayTime }}
								</text>
							</view>
							<view class="btns">
								<!-- isDiscard == 1 表示已经作废 -->
								<u-button type="primary" v-if="vd.isDiscard == 1" size="mini" @click="resubmit(vd)">重新填报</u-button>
								<view v-else class="btnsItem">
									<!-- 如果已经上传了装车榜单(吨位和图片)，就不能再作废 -->
									<u-button type="primary" size="mini" @click="confirmation(vd.dataChangeMsgs)" v-if="vd?.dataChangeMsgs?.length">
										{{ Props.type == 2 ? '确认收款' : '确认通知' }}
									</u-button>
									<u-button type="primary" v-if="[1, 2, 3].includes(+vd.vehicleState)" size="mini" @click="bdManager(vd)">装/卸榜单</u-button>
									<!-- 车辆未装车之前都可以撤销，也就是说：未到场，已到厂都可以撤销 -->
									<u-button type="primary" v-if="[1, 2].includes(+vd.vehicleState)" size="mini" @click="cancellation(vd)">作废</u-button>
									<!-- 车辆装车后，无法进行撤销，只能进行【换车/换司机】，卸车后，啥也不显示 -->
									<!-- <u-button type="primary" size="mini" @click="changeInformation(vd, item)">换车/换司机</u-button> -->
									<u-button type="primary" v-if="[3].includes(+vd.vehicleState)" size="mini" @click="changeInformation(vd)">换车/换司机</u-button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</z-paging>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import http from '@/common/request.js';
import { onLoad, onUnload, onShow, onHide, onReady } from '@dcloudio/uni-app';
import { navTo, setLoadingToast, setToast } from '@/common/utils';
import { confirmNotify, discardCar, getUseByCarList } from '@/api/logisitcsCompany';
import dropDownVue from '../../../../components/dropDown/dropDown.vue';

const Props = defineProps({
	//  1进行中(填完需求提交) 2已完成(已上传卸车)  3作废
	type: {
		type: Number
	},
	tabIndex: {
		type: Number
	},
	currentIndex: {
		type: Number
	}
});

// 当前组件是否已经加载过了
const firstLoaded = ref(false);
// 是否滚动到当前页
const isCurrentPage = ref(false);
//
const dataList = ref([]);
const paging = ref(null);
const cache = {};

watch(
	() => Props.currentIndex,
	(newVal) => {
		if (newVal === Props.tabIndex) {
			// 懒加载，当滑动到当前的item时，才去加载
			if (!firstLoaded.value) {
				// 这里需要延迟渲染z-paging的原因是为了避免在一些平台上立即渲染可能引发的底层报错问题
				setTimeout(() => {
					isCurrentPage.value = true;
				}, 100);
			}
		}
	},
	{
		immediate: true
	}
);

// 运费状态筛选
const dropOk = (datas) => {
	// 0-未付款，1-已付款,2-报废
	const values = {
		fk: 1,
		wfk: 0
	};
	if (datas[0]) {
		cache.inputFreightState = values[datas[0].value];
	} else {
		cache.inputFreightState = '';
	}

	queryList();
};

// 车辆信息作废
const cancellation = (vd) => {
	uni.showModal({
		title: '提示',
		content: '是否确认报废当前车辆信息？',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		success: (res) => {
			if (res.confirm) {
				setLoadingToast('处理中');
				try {
					discardCar({ id: vd.id, needId: vd.id, isDiscard: 1 }).then((res) => {
						uni.hideLoading();
						queryList();
						setToast('操作成功');
					});
				} catch (e) {
					console.log('e === ', e);
					//TODO handle the exception
					uni.hideLoading();
				}
			}
		},
		fail: () => {},
		complete: () => {}
	});
};
// 换车换司机
const changeInformation = (vd) => {
	navTo('/pages/logisticsCompany/index/declaration/changeDriver/changeDriver', { vd });
};

// 管理榜单
const bdManager = (vd) => {
	navTo('/pages/logisticsCompany/index/declaration/uploadBd/uploadBd', { vd });
};

//
const descriptionGet = (data) => {
	let str = '';
	const changeData = {};
	data.forEach(({ notify, msgType, content }) => {
		if (+msgType == 0) {
			const changeMap = JSON.parse(content);
			changeMap.forEach(({ fieldName, newValue }) => {
				switch (fieldName) {
					case '运费单价':
						changeData[fieldName] = `运费单价发生改变,更改后的运价为:${newValue}`;
						break;
					case '装车地点':
						changeData[fieldName] = `装车地点发生改变，新装车地点为:${newValue}`;
						break;
					case '卸车地点':
						changeData[fieldName] = `卸车地点发生改变，新卸货地址为:${newValue}`;
						break;
					default:
						break;
				}
			});
			// 当前车辆卸车地点发生改变，新卸货地址为:河南省郑州市，运价为:780，确认无误请点击下方`确认通知`确认收到。
		}

		if (+msgType == 2) {
			changeData['sktz'] = content;
		}
	});

	for (let key in changeData) {
		str += changeData[key] + '。';
	}

	return str + '确认无误请点击下方`确认通知`确认收到。';
};

// 已作废的订单重新填报
const resubmit = (vd) => {
	uni.showModal({
		title: '提示',
		content: '是否重新填报当前车辆信息？',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		success: (res) => {
			if (res.confirm) {
				setLoadingToast('处理中...');
				try {
					discardCar({ id: vd.id, needId: vd.needId, isDiscard: 0 }).then((res) => {
						uni.hideLoading();
						queryList();
						setToast('操作成功');
					});
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading();
				}
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

// 确认通知
const confirmation = (data) => {
	const dataIds = data.map((v) => v.id);
	uni.showModal({
		title: '通知',
		content: '请确认信息已核实无误。',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		success: async (res) => {
			if (res.confirm) {
				setLoadingToast('操作中...');
				try {
					// 使用 Promise.all 等待所有 confirmNotify 执行完毕
					await Promise.all(dataIds.map((id) => confirmNotify({ id })));
					uni.hideLoading();
					queryList();
				} catch (e) {
					// 处理异常
					uni.hideLoading();
				}
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const queryList = (pageNumber, pageSize, filterText) => {
	if (pageNumber) {
		cache.pageNumber = pageNumber;
		cache.pageSize = pageSize;
	} else {
		cache.filterText = filterText;
	}

	// 如果是3 表示是已作废
	if (Props.type == 3) {
		cache.inputFreightState = 2;
	}
	// console.log('cache ===> ', cache);
	getUseByCarList({ ...cache, state: Props.type }).then((res) => {
		firstLoaded.value = true;
		console.log('res.data.rows ===>  ', res.data.rows);
		paging.value.complete(res.data.rows);
	});
};

const uniOn = () => {
	console.log('res.data.rows ===>  zx');
	setTimeout(() => {
		queryList();
	});
};

onLoad(() => {
	uni.$on('uploadOk', uniOn);
});

onUnload(() => {
	uni.$off('uploadOk', uniOn);
});
</script>

<style scoped lang="scss">
.conLines {
	border-bottom: 6rpx solid #f8f8f8;
}

.searchBox {
	padding: 10rpx;
}

.container {
	padding: 20rpx 30rpx;

	.shopType {
		font-size: 28rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 0;

		.freightDetails {
			margin-left: auto;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.icon {
				width: 30rpx;
				height: 30rpx;
				margin-right: 30rpx;
				transform: rotateY(180deg);
			}
		}

		.circle {
			margin-right: 10rpx;
			font-size: 24rpx;
			display: flex;
			width: 40rpx;
			height: 40rpx;
			background-color: #51a9ec;
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			color: #fff;
		}
	}

	.con {
		display: flex;
		flex-direction: column;
		// border: 1rpx solid red;
		// background-color: #fff;

		.conRow {
			display: flex;
		}

		.item {
			flex: 1;
			padding: 10rpx 0;
			// border: 1px solid red;
			display: flex;
			justify-content: space-between;

			.type {
				color: #bdbdbd;
				font-size: 26rpx;
			}

			.unit {
				font-size: 23rpx;
			}

			.rightBox {
				display: flex;
				align-items: center;

				.text {
					font-weight: 500;
					font-size: 26rpx;
					width: 500rpx;
					text-align: right;
				}

				.img {
					width: 35rpx;
					height: 35rpx;
					margin-left: 10rpx;
				}
			}
		}
	}
}

.btns {
	padding: 15rpx 0;
	text-align: right;
	// border: 1rpx solid red;

	& > *,
	.btnsItem {
		& > * {
			margin-left: 15rpx;
		}
	}
}

.notify {
	background: #ffffb3;
	color: #000;

	.type {
		color: #606060 !important;
	}
}
</style>
